<template>
  <MyModal ref="myModal" title="修改余额" :top="40" :width="700">
    <template #content>
      <a-form
        ref="loginForm"
        :rules="rules"
        :model="formState"
        :label-col="labelCol"
        style="width: 500px"
      >
        <!-- <a-form-item name="userName" label="用户名">
          <a-input
            :disabled="true"
            v-model:value="formState.userName"
            style="width: 200px"
          ></a-input>
        </a-form-item> -->

        <a-form-item name="keyword" label="类型">
          <a-select v-model:value="formState.type" placeholder="类型" style="width: 200px">
            <a-select-option v-for="(item, index) in typeList" :key="index" :value="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <!-- <a-form-item
          label="验证码"
          name="code"
          :rules="[{ required: true, message: '请输入验证码!' }]"
        >
          <a-input
            v-model:value="formState.code"
            placeholder="验证码"
            autocomplete="off"
            style="width: 200px"
          >
            <template #prefix><MailOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
          </a-input>
          <a-button
            :disabled="myState.smsSendFlag"
            v-text="(!myState.smsSendFlag && '获取验证码') || `${myState.time} s`"
            @click="getSms"
            style="margin-left: 15px"
            type="primary"
          ></a-button>
        </a-form-item> -->

        <a-form-item name="content" label="充值金额">
          <a-input
            v-model:value="formState.content"
            placeholder="充值金额"
            style="width: 200px"
          ></a-input>
        </a-form-item>
      </a-form>

      <div
        style="
          border-top: 1px solid #f0f0f0;
          text-align: right;
          padding-top: 10px;
          padding-right: 10px;
        "
      >
        <a-button @click="() => myModal.cancelModal()" style="margin-right: 10px">取消</a-button>
        <a-button type="primary" @click="handleSubmit">确定</a-button>
      </div>
    </template>
  </MyModal>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { regYuanToFen } from '@/hooks/util'
import { useUserStore } from '@/store/modules/user'
import * as userApi from '@/api/user'
import * as assetsOrderApi from '@/api/assetsOrder'
import { message } from 'ant-design-vue'

const userStore = useUserStore()
onMounted(async () => {
  await userStore.getUserInfo()
  formState.value.userName = userStore.userInfo.userName as string
  // console.log('formState.value.userName=', formState.value.userName)
})

const myModal = ref()
const loginForm = ref()

let userId = ref<string>('')
const showModal = (id: string) => {
  userId.value = id
  myModal.value?.showModal()
}

const emit = defineEmits<{
  refresh: []
}>()

defineExpose({
  showModal,
})

const myState = reactive({
  smsSendFlag: false,
  time: 60,
})

// 获取验证码
const getSms = async () => {
  loginForm.value?.validateFields(['userName']).then(async () => {
    let params = {
      phone: formState.value.userName,
    }
    if (params['phone'] == '') {
      message.error(`用户名不能为空~`)
      return
    }

    const hide = message.loading('验证码发送中..', 0)
    try {
      let { state, message } = await userApi.sendRegSms(params)
      if (state === 200) {
        myState.smsSendFlag = true
        const interval = setInterval(() => {
          if (myState.time-- <= 0) {
            myState.time = 60
            myState.smsSendFlag = false
            clearInterval(interval)
          }
        }, 1000)
      } else {
        message.error(message)
      }
    } catch (error) {
      message.error('网络请求连接失败~')
    }
    setTimeout(hide, 1)
  })
}

import type { RuleObject } from 'ant-design-vue/es/form/interface'
let validateChangeBalance = async (rule: RuleObject, value: string) => {
  value = String(value)
  if (value == null || value.trim() === '') {
    return Promise.reject('金额不能为空')
  }

  // 使用正则表达式来验证金额格式，允许整数和小数点后两位
  const regex = /^\d+(\.\d{1,2})?$/
  if (!regex.test(value)) {
    return Promise.reject('请输入有效的金额（整数或小数点后两位）')
  }

  // 将字符串转换为数字并检查是否大于0
  const amount = parseFloat(value)
  if (isNaN(amount) || amount <= 0) {
    return Promise.reject('请输入大于0的金额')
  }

  // 如果一切正常，返回成功
  return Promise.resolve()
}
import type { Rule } from 'ant-design-vue/es/form'
const rules: Record<string, Rule[]> = {
  content: [{ required: true, validator: validateChangeBalance, trigger: 'blur' }],
}

let labelCol = { span: 6 }
interface FormState {
  type: number
  content: string
  code: string
  userName: string
}
const formState = ref<FormState>({
  type: 1,
  content: '',
  code: '',
  userName: '',
})

import type { SelectProps } from 'ant-design-vue'
const typeList = ref<SelectProps['options']>([
  {
    label: '加钱',
    value: 1,
  },
  {
    label: '扣钱',
    value: 0,
  },
])

const handleSubmit = async () => {
  let params = {
    amount: regYuanToFen(formState.value.content, 100),
    type: formState.value.type,
    userId: userId.value,
  }

  // console.log('params=', params)

  loginForm.value.validate().then(async () => {
    try {
      let { state, message: msg } = await assetsOrderApi.editUserBalance(params)
      if (state === 200) {
        message.success('操作成功')
        emit('refresh')
        myModal.value.cancelModal()
      } else {
        message.error(msg)
      }
    } catch (error) {
      message.error('网络请求连接失败~')
    }
  })
}
</script>
